package net.zdsoft.wpchat.android.client;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.sf.json.JSONObject;
import net.zdsoft.keel.action.Action;
import net.zdsoft.keel.action.ActionContext;
import net.zdsoft.keel.action.ActionInvoker;
import net.zdsoft.keel.interceptor.Interceptor;
import net.zdsoft.keel.util.ActionUtils;
import net.zdsoft.keel.util.ServletUtils;
import net.zdsoft.wpchat.support.client.MemoryUser;

/**
 * 权限拦截器
 * 
 * @author xuan
 * @version $Revision: 1.0 $, $Date: 2014-9-22 下午10:41:18 $
 */
public class AuthorizerInterceptor implements Interceptor {
    private static Logger logger = LoggerFactory.getLogger(AuthorizerInterceptor.class);

    @Override
    public void init() {
    }

    @Override
    public void destroy() {
    }

    @Override
    public String intercept(ActionInvoker actionInvoker) throws Exception {
        String namespace = actionInvoker.getActionPackage().getNamespace();
        String actionName = actionInvoker.getServiceMapping().getMarkedName();
        String actionPath = namespace + "/" + actionName;
        logger.debug("actionPath: {}", actionPath);

        MemoryUser user = (MemoryUser) ActionContext.getSession().getAttribute(MemoryUser.KEY);
        if (user == null) { // 用户没有登录或超时，memoryUser 为空
            ActionContext.getSession().setAttribute(Action.LOGIN, true);

            if (ActionUtils.isJsonAction(actionInvoker)) {
                printRefreshPageJson();
            }
            else {
                return Action.LOGIN;
            }

            return Action.NONE;
        }

        return actionInvoker.invoke();
    }

    /**
     * 将刷新页面的脚本以 JSON 方式输出。
     */
    protected void printRefreshPageJson() throws IOException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("script", "location.href = location.href;");
        jsonObject.put("actionErrors", new String[] { "对不起，您没有登录或者已经超时，系统将转向登录页面！" });
        ServletUtils.print(ActionContext.getResponse(), jsonObject.toString(), "application/json");
    }

}
